import axios from "axios"; // 引用axios
import { Toast } from 'vant'

const request = axios.create({
    // baseURL: 'http://192.168.199.234:29081',
    // baseURL:'/tophappiness',
    baseURL: process.env.NODE_ENV === "production" ? process.env.VUE_APP_BASE_API : "/tophappiness",
    timeout: 6000,
    // headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});

function startLoading() {
    // 开始加载
    Toast.loading({
        message: '加载中...',
        forbidClick: true,
    });
}
function endLoading() {
    // 结束加载
    Toast.clear()
}

request.interceptors.request.use(config => {
    startLoading()
    return config
}, error => {
    Promise.reject(error)
})

request.interceptors.response.use(
    response => {
        endLoading()
        return Promise.resolve(response.data)
    },
    error => {
        startLoading()
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    console.log(401)
                    break;
                case 403:
                    console.log(403)
                    break;
                case 404:
                    Toast({
                        message: '网络请求不存在',
                        duration: 1500,
                        forbidClick: true
                    })
                    console.log(404)
                    break;
                case 500:
                    console.log(500)
                    break;
            }
        }
        return Promise.reject(error.response)
    }
)
//get请求
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        request
            .get(url, {
                params: params,
            })
            .then((response) => {
                resolve(response);
            })
            .catch((err) => {
                reject(err);
            });
    });
}
//post请求
export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        request.post(url, data).then(
            (response) => {
                resolve(response.data);
            },
            (err) => {
                reject(err);
            }
        );
    });
}
//put请求
export function put(url, data = {}) {
    return new Promise((resolve, reject) => {
        request.post(url, data).then(
            (response) => {
                resolve(response.data);
            },
            (err) => {
                reject(err);
            }
        );
    });
}
export default {
    get,
    post,
    put,
}
